package com.jzit.network.intercept

import com.jzit.network.utils.LogUtils
import okhttp3.Interceptor
import okhttp3.Response
import org.json.JSONObject
import java.lang.Exception
import java.nio.charset.Charset

/*
    ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
       Author   :  zhouxc
       Date     :  2022/10/26
       Time     :  14:40
    ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
 */
private const val TAG = "RETROFIT_LOG"

class ResponseLogInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val buffer = response.body()?.source()?.buffer()
        response.body()?.source()?.request(Long.MAX_VALUE)
        val json = buffer?.clone()?.readString(Charset.forName("UTF-8"))
        request?.apply {
            json?.apply {
                try {
                    LogUtils.logD(
                        TAG,
                        "response : ${request.url()}\n${JSONObject(json).toString(4)}"
                    )
                } catch (e: Exception) {
                    LogUtils.logD(TAG, "response : json  解析出错了  $json")
                }

            }
        }

        return response
    }
}